<script setup lang="ts">
import { ref } from "vue"
import { ElMessage } from "element-plus"
import { sumValuesForName } from "@/utils/common"

const buttonLoading = ref(false)
const dialogTableVisible = ref(false)
const tableData = ref<any>([])

const handleClose = () => {
  input.value = ""
  uid.value = 0
  buttonLoading.value = false
  dialogTableVisible.value = false
  emit("dialogClose", true)
}
const emit = defineEmits(["dialogClose"])
//#region batchEdit-head
const input = ref("")
const listData = ref<any>([])
const uid = ref<number>(0)
//#endregion
//#region vxe-grid
import Decimal from "decimal.js"
import { getAdminRoleListApi } from "@/api/system"
import { generatePrice, generateDiscount } from "@/utils/common"
import { batchEditApi } from "@/api/billv2"
import { VxeTablePropTypes } from "vxe-table"

// const sumNum = (list: any, field: string) => {
//   let count = 0
//   list.forEach((item: any) => {
//     count += Number(item[field])
//   })
//   return count
// }

const footerMethod: VxeTablePropTypes.FooterMethod<any> = ({ columns, data }) => {
  return [
    columns.map((column, columnIndex) => {
      if (columnIndex === 0) {
        return "统计"
      }
      if (["billAmount", "enter_discount", "enter_finally"].includes(column.field)) {
        return sumValuesForName(data, column.field)
      }

      return null
    })
  ]
}

const handleInput = (row: any) => {
  const { finallyAmount, discountAmount } = generatePrice(
    row.enter_price,
    row.enter_finally,
    row.enter_discount,
    row.billAmount,
    false
  )
  // row.enter_price = price
  row.enter_finally = finallyAmount
  row.enter_discount = discountAmount
}
const handleDiscount = (row: any) => {
  const { price, finallyAmount } = generateDiscount(
    row.enter_price,
    row.enter_finally,
    row.enter_discount,
    row.billAmount,
    false
  )
  row.enter_price = price
  row.enter_finally = finallyAmount
  // row.enter_discount = discountAmount
}
const handleFinally = (row: any) => {
  const billAmount = new Decimal(row.billAmount).times(10000)
  const enter_finally = new Decimal(row.enter_finally)
  const discountAmount = billAmount.minus(enter_finally).toNumber()
  const { price } = generateDiscount(row.enter_price, row.enter_finally, discountAmount, billAmount.toString(), true)
  row.enter_price = price.toFixed(2)
  // row.enter_finally = finallyAmount
  row.enter_discount = discountAmount
}

//#endregion
const handleSubmit = () => {
  batchEdits()
}
const batchEdits = async () => {
  buttonLoading.value = true
  await batchEditApi({
    batch_list: JSON.stringify(tableData.value),
    type: "warehouse"
  })
  buttonLoading.value = false
  ElMessage.success("修改成功")
  handleClose()
}
const showClick = async (row: any) => {
  console.log(row)
  const column = Object.values(row).map((item: any) => item["bill_back_user"])

  let isbool = false
  let condition = ""
  column.map((item: any) => {
    if (condition == "") {
      condition = item
    } else {
      if (item != condition) {
        isbool = true
      }
    }
  })
  if (isbool) {
    ElMessage.warning("请勾选相同客户的票据")
    return
  }
  const uidColumn: any = Object.values(row)
  uid.value = uidColumn[0].out_admin_id
  input.value = condition
  await getAdminList()
  tableData.value = Object.values(row)
  dialogTableVisible.value = true
}

const getAdminList = async () => {
  await getAdminRoleListApi({
    role_ids: 2
  })
    .then((res) => {
      listData.value = res.data
    })
    .catch(() => {})
    .finally(() => {})
}

const sexList1 = ref([
  { label: "是", value: 1 },
  { label: "否", value: 2 }
])
const formatSex = (value: number) => {
  if (value === 1) {
    return "是"
  }
  if (value === 2) {
    return "否"
  }
  return ""
}
const setAllEnterInvoicings = (value: number) => {
  tableData.value.forEach((row: any) => {
    row.enter_invoicings = value
  })
}
const setAllEnterChecks = (value: number) => {
  tableData.value.forEach((row: any) => {
    row.enter_checks = value
  })
}

const value2 = ref("")
const shortcuts = [
  {
    text: "今天",
    value: new Date()
  },
  {
    text: "昨天",
    value: () => {
      const date = new Date()
      date.setDate(date.getDate() - 1)
      return date
    }
  },
  {
    text: "一周前",
    value: () => {
      const date = new Date()
      date.setDate(date.getDate() - 7)
      return date
    }
  }
]
const handleDateChange = (value: any) => {
  tableData.value.forEach((row: any) => {
    row.enter_time = value
  })
  console.log(value)
}
const customDateTimeFormat = ref<string>("YYYY-MM-DD HH:mm:ss")
defineExpose({ showClick }) //暴露子组件的方法或者数据
</script>

<template>
  <el-dialog
    v-model="dialogTableVisible"
    title="修改"
    draggable
    destroy-on-close
    width="80%"
    :before-close="handleClose"
  >
    <div class="batchEdit-head">
      <div class="batchEdit-head-box">
        <div class="title">企业:</div>
        <div><el-input v-model="input" disabled placeholder="请输入" /></div>
      </div>
      <div class="batchEdit-head-box">
        <div class="title">业务员:</div>
        <div>
          <el-select v-model="uid" placeholder="请选择" disabled>
            <el-option v-for="item in listData" :key="item.id" :label="item.nickname" :value="item.id" />
          </el-select>
        </div>
      </div>
    </div>
    <el-divider />
    <div class="heads">
      <div class="bolck">
        <el-button type="primary" @click="setAllEnterInvoicings(1)">一键开票</el-button>
        <el-button type="primary" @click="setAllEnterInvoicings(2)">取消开票</el-button>
      </div>
      <div class="bolck">
        <el-button type="primary" @click="setAllEnterChecks(1)">一键先款先票</el-button>
        <el-button type="primary" @click="setAllEnterChecks(2)">取消先款先票</el-button>
      </div>
      <div class="bolck">
        <el-date-picker
          v-model="value2"
          type="datetime"
          placeholder="请选择"
          :shortcuts="shortcuts"
          :format="customDateTimeFormat"
          :value-format="customDateTimeFormat"
          @change="handleDateChange"
        />
      </div>
    </div>
    <vxe-table
      border
      show-overflow
      :data="tableData"
      show-footer
      :column-config="{ resizable: true }"
      :edit-config="{ trigger: 'click', mode: 'cell' }"
      :footer-method="footerMethod"
    >
      <vxe-column type="seq" width="60" />
      <vxe-column field="acceptorName" title="承兑人" />
      <vxe-column field="billAmount" title="票面金额" width="180" />
      <vxe-column field="expirationDate" title="到期日" width="180" />
      <vxe-column field="billNo" title="票号" width="180" />
      <vxe-column
        field="enter_price"
        title="每十万价格"
        :edit-render="{ name: 'input', attrs: { type: 'number', placeholder: '请输入' } }"
      >
        <template #edit="{ row }">
          <vxe-input v-model="row.enter_price" @input="handleInput(row)" type="number" placeholder="请输入" />
        </template>
      </vxe-column>
      <vxe-column
        field="enter_discount"
        title="贴息费"
        :edit-render="{ name: 'input', attrs: { type: 'number', placeholder: '请输入' } }"
      >
        <template #edit="{ row }">
          <vxe-input v-model="row.enter_discount" @input="handleDiscount(row)" type="number" placeholder="请输入" />
        </template>
      </vxe-column>
      <vxe-column
        field="enter_finally"
        title="实付金额"
        :edit-render="{ name: 'input', attrs: { type: 'number', placeholder: '请输入' } }"
      >
        <template #edit="{ row }">
          <vxe-input v-model="row.enter_finally" @input="handleFinally(row)" type="number" placeholder="请输入" />
        </template>
      </vxe-column>
      <vxe-column field="enter_time" title="入库时间" :edit-render="{}">
        <template #edit="{ row }">
          <vxe-input v-model="row.enter_time" type="datetime" placeholder="请选择入库时间" transfer />
        </template>
      </vxe-column>
      <vxe-column field="enter_invoicings" title="开票" :edit-render="{}">
        <template #default="{ row }">
          <span>{{ formatSex(row.enter_invoicings) }}</span>
        </template>
        <template #edit="{ row }">
          <vxe-select v-model="row.enter_invoicings" transfer>
            <vxe-option v-for="item in sexList1" :key="item.value" :value="item.value" :label="item.label" />
          </vxe-select>
        </template>
      </vxe-column>
      <vxe-column field="enter_checks" title="先款先票" :edit-render="{}">
        <template #default="{ row }">
          <span>{{ formatSex(row.enter_checks) }}</span>
        </template>
        <template #edit="{ row }">
          <vxe-select v-model="row.enter_checks" transfer>
            <vxe-option v-for="item in sexList1" :key="item.value" :value="item.value" :label="item.label" />
          </vxe-select>
        </template>
      </vxe-column>
      <vxe-column
        field="remark"
        title="备注"
        :edit-render="{ name: 'textarea', attrs: { type: 'textarea', placeholder: '请输入' } }"
      >
        <template #edit="{ row }">
          <vxe-textarea v-model="row.remark" placeholder="请输入" :autosize="{ minRows: 2, maxRows: 4 }" />
        </template>
      </vxe-column>
    </vxe-table>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="handleSubmit" :loading="buttonLoading"> 确认 </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">
.el-button--text {
  margin-right: 15px;
}
.el-select {
  width: 300px;
}
.el-input {
  width: 300px;
}
.dialog-footer button:first-child {
  margin-right: 10px;
}

.batchEdit-head {
  display: flex;
  justify-content: flex-start;
}
.batchEdit-head .batchEdit-head-box {
  display: flex;
  align-items: center;
  margin-right: 10px;
}
.batchEdit-head .batchEdit-head-box .title {
  margin-right: 10px;
}
.heads {
  display: flex;
  justify-content: end;
  margin-bottom: 10px;
}
.heads .bolck {
  margin-left: 10px;
}
</style>
